#include <algorithm>
using namespace std;
/*
 * @lc app=leetcode.cn id=99 lang=cpp
 *
 * [99] 恢复二叉搜索树
 */

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
typedef long long ll;
class Solution {
public:
    // 采用中序遍历的思想求解
    // ll prev = LLONG_MIN; TreeNode* temp = nullptr, *next = nullptr, *pre = nullptr;

    // void recoverTree(TreeNode* root) {
    //     inorder(root);
    //     if (temp && next) {
    //         swap(temp->val, next->val);
    //     }
    // }
    // void inorder(TreeNode* root) {
    //     if (root) {
    //         inorder(root->left);
    //         if (root->val < prev && temp) {
    //             next = root;
    //         }
    //         if (root->val < prev && !temp) {
    //             temp = pre; next = root;
    //         }
    //         prev = root->val;
    //         pre = root;
    //         inorder(root->right);
    //     } 
    // }

    // 标答采用Morris中序便利的思想
};
// @lc code=end

